﻿#include <QEventLoop>
#include "MainWindow.h"
#include <QTimer>
#include <QPushButton>
#include "./ui_MainWindow.h"
#include "common_trigger/utils/utils.h"
#include "libdaq/device/base_device.h"
#include "common_trigger/connect_page/connect_page.h"

using namespace libdaq::device;

MainWindow::MainWindow(QWidget *parent)
  : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);
  qRegisterMetaType<std::vector<std::vector<float> > >("std::vector<std::vector<float>>");
  // 创建设备
  base_device_ = NewDevice();
  connect(ui->Connnectbutton, &QPushButton::clicked, this, &MainWindow::ClickConnectAction);
  connect(ui->StartADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStartADCCollectionAction);
  connect(ui->UpdateConfig, &QPushButton::clicked, this, &MainWindow::ClickUpdateConfig);
  connect(ui->OnceCollection, &QPushButton::clicked, this, &MainWindow::ClickSoftwareTrigger);
  connect(ui->StopADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStopADCCollection);

  InitWaveWidget();

}

MainWindow::~MainWindow() {
  if (common_trigger_thread_ != nullptr) {
    common_trigger_thread_->quit();
    common_trigger_thread_.reset();
  }
  delete ui;
}

void MainWindow::ConnectStatusSlot(bool status, ConnectPage::ConnectType type) {
  if (status) {
    if (!base_device_->InitializeDevice()) {
      qWarning(u8"初始化设备失败，请检查配置参数是否存在错误");
      return;
    }
    if (!base_device_->ConnectedDevice()) {
      qWarning(u8"发送连接设备命令失败");
      return;
    }

  }
}

void MainWindow::ClickConnectAction() {
  ConnectPage connect_page(base_device_, nullptr);
  // 初始化连接界面
  if (connect_page_.isNull()) {
    connect_page_.reset(new ConnectPage(base_device_));
    connect_page_->setModal(false);
    connect(connect_page_.get(), &ConnectPage::ConnectStatus, this, &MainWindow::ConnectStatusSlot);
  }
  connect_page_->InitParams(base_device_);
  connect_page_->show();
}

void MainWindow::ClickStartADCCollectionAction() {

  is_collecting = true;

  CommonTrigger();
  qInfo(u8"软件触发成功");
}

void MainWindow::ClickUpdateConfig() {
  // 采样率 800K
  auto legal_sample_rate = base_device_->GetADCLegalSampleRate();
  if (!base_device_->ConfigADCSampleRate(libdaq::device::LockzhinerADCSampleRate::ADCSampleRate_800_K)) {
    qWarning(u8"采样率配置失败");
  }
  // 电压量程 10V
  if (!base_device_->ConfigADCVoltage(libdaq::device::LockzhinerADCVoltage::ADCVoltage_10_V)) {
    qWarning(u8"电压量程配置失败");
  }
  // 8通道使能
  if (!base_device_->ConfigADCChannel(0xFF)) {
    qWarning(u8"ADC8通道配置失败");
  }
  // 触发电平 0mv
    uint32_t level=0;
   // 双边缘触发 普通采集 普通触发
    auto type = static_cast<libdaq::device::LockzhinerADCTriggerType>(libdaq::device::LockzhinerADCTriggerType::DoubleEdge);
    auto mode = static_cast<libdaq::device::LockzhinerADCTriggerMode>(libdaq::device::LockzhinerADCTriggerMode::Common);
    auto channel = static_cast<libdaq::device::LockzhinerADCChannel>(libdaq::device::LockzhinerADCChannel::ADCChannelAINNone);
    if (!base_device_->ConfigADCTrigger(type, mode, channel, level)) {
        qWarning(u8"DAQ控制器配置ADC触发失败");
    }

  // 长度 4920个点
    if (!base_device_->ConfigADCTriggerLength(4920)) {
        qWarning(u8"触发长度配置失败");
    }
  // 超时 100ms
    if (!base_device_->ConfigTriggerTimeout(100)) {
        qWarning(u8"超时时间配置失败");
    }

  // AC/DC 设置为DC
  uint8_t enable = 0x0F;
  if (!base_device_->ConfigACDC(enable)) {
    qWarning("配置AC/DC失败");
    return;
  }
  qInfo(u8"下发配置成功");
}

void MainWindow::ClickSoftwareTrigger()
{
  if(!base_device_->ConfigADCTriggerSource
  (static_cast<uint8_t>(libdaq::device::DAQADCTriggerSource::TriggerSourceSoftware))){
    qWarning(u8"软件触发失败");
    return;
  }
  qInfo(u8"软件触发成功");
}

void MainWindow::ClickStopADCCollection()
{
  is_collecting = false;
  if(!base_device_->StopADCCollection()){
    qWarning(u8"停止ADC采集失败");
    return;
  }
  if (common_trigger_thread_ != nullptr) {
      common_trigger_thread_->quit();
      common_trigger_thread_->deleteLater();
      common_trigger_thread_ = nullptr;
  }
  qInfo(u8"停止ADC采集成功");
}

void MainWindow::InitWaveWidget() {
  QVector<Qt::GlobalColor> channel_color_ = { // 通道颜色
    Qt::red, Qt::green, Qt::cyan, Qt::blue, Qt::yellow, Qt::magenta, Qt::gray, Qt::darkRed
  };
  base_wave_widget_ = QSharedPointer<BaseWaveWidget>::create();
  base_wave_widget_->InitChannel(8, channel_color_);
  ui->stackedWidget->addWidget(base_wave_widget_.get());
  ui->stackedWidget->setCurrentWidget(base_wave_widget_.get());
}

void MainWindow::CommonTrigger()
{
  if(!is_collecting){
    return;
  }

  if (common_trigger_thread_ != nullptr) {
    common_trigger_thread_->quit();
    common_trigger_thread_->deleteLater();
    common_trigger_thread_ = nullptr;
  }

  if(!base_device_->StartADCCollection()){
    qWarning(u8"启动ADC采集失败");
    return;
  }

  common_trigger_thread_ = QSharedPointer<CommonTriggerADCThread>::create(base_device_);
  connect(common_trigger_thread_.get(), &CommonTriggerADCThread::SendData, this, &MainWindow::UpdatePlotData);
  common_trigger_thread_->start();
}
void MainWindow::UpdatePlotData(const std::vector<std::vector<float> > &data) {
    // 判断数据是否为空
    bool is_empty = true;
    for (const auto &i: data) {
        if (!i.empty()) {
            is_empty = false;
            break;
        }
    }
    if (is_empty) {
        return;
    }

    base_wave_widget_->Clear();

    // 添加数据到图表
    for (int i = 0; i < data.size(); ++i) {
        for (int j = 0; j < data.at(i).size(); ++j) {
            base_wave_widget_->AddData(i, data[i][j]);
        }
    }

    // 更新图表
    base_wave_widget_->xAxis->setRange(0, 4920);
    base_wave_widget_->replot(QCustomPlot::rpQueuedReplot);

    CommonTrigger();
}

